package com.lelefly.base.controller;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.model.Result;
import com.lelefly.base.po.LeleflyUser;
import com.lelefly.base.po.RegInfo;
import com.lelefly.base.po.UavDistributor;
import com.lelefly.base.utils.RandomUTils;
import com.lelefly.constant.Constant;
import com.lelefly.handleexecption.ServiceExecption;

@Controller
@RequestMapping("/reg")
public class RigistMessageCodeController extends BaseController {

	@Resource
	public BaseDao baseDao;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/getMes", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Result getMes(String tel) {
		Result resultlist = new Result<>();
		try {
			if (StringUtils.isEmpty(tel)) {
				throw new ServiceExecption("参数错误");
			}
			String hql1 = "from LeleflyUser as mdoel where phonenumber='" + tel
					+ "'";
			LeleflyUser leleflyUser = (LeleflyUser) baseDao
					.getObjcetReUnique(hql1);
			if (leleflyUser != null) {
				throw new ServiceExecption("该用户已注册");
			}
			String hql = "from RegInfo as mdoel where tel='" + tel + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			if (regInfo == null) {
				regInfo = new RegInfo();
				regInfo.setTel(tel);
				regInfo.setCount(1);
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
			} else {
				if ((System.currentTimeMillis() - Long.valueOf(regInfo
						.getExpiredTime())) >= 1000 * 60 * 60 * 24) {
					regInfo.setCount(0);
				}
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
				regInfo.setCount(regInfo.getCount() + 1);
			}
			String code = RandomUTils.fix(
					String.valueOf((int) (Math.random() * 10000 + 1)), 4);
			regInfo.setRegCode(code);
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			restAPI.init(Constant.SERVER, Constant.PORT);// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(Constant.ACCOUNT, Constant.TOKEN);
			restAPI.setAppId(Constant.APPID);// 初始化应用ID
			result = restAPI.sendTemplateSMS(tel, Constant.TEMPLATESID,
					new String[] { regInfo.getRegCode() });
			if ("000000".equals(result.get("statusCode"))) {
				HashMap<String, Object> data = (HashMap<String, Object>) result
						.get("data");
				Set<String> keySet = data.keySet();
				for (String key : keySet) {
					Object object = data.get(key);
					getLogger().info(key + " = " + object);
				}
				baseDao.saveOrUpdateObject(regInfo);
				resultlist.setState(Constant.HTTP_STATUS_OK);
			} else {
				resultlist.setState(Constant.HTTP_STATUS_FAIL);
				resultlist.setMes((String) result.get("statusMsg"));
				getLogger().info(
						"错误码=" + result.get("statusCode") + " 错误信息= "
								+ result.get("statusMsg"));
			}
		} catch (Exception e) {
			// TODO: handle exception
			getLogger().info(e.getLocalizedMessage());
			resultlist.setState(Constant.HTTP_STATUS_FAIL);
			resultlist.setMes("服务器错误,稍后再试");
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			resultlist.setState(Constant.HTTP_STATUS_FAIL);
			resultlist.setMes(e.getMessage());
		}
		return resultlist;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/getResetMes", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Result getResetMes(String tel) {
		Result resultlist = new Result<>();
		try {
			if (StringUtils.isEmpty(tel)) {
				throw new ServiceExecption("参数错误");
			}
			String hql = "from RegInfo as mdoel where tel='" + tel + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			if (regInfo == null) {
				regInfo = new RegInfo();
				regInfo.setTel(tel);
				regInfo.setCount(1);
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
			} else {
				if ((System.currentTimeMillis() - Long.valueOf(regInfo
						.getExpiredTime())) >= 1000 * 60 * 60 * 24) {
					regInfo.setCount(0);
				}
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
				regInfo.setCount(regInfo.getCount() + 1);
			}
			String code = RandomUTils.fix(
					String.valueOf((int) (Math.random() * 10000 + 1)), 4);
			regInfo.setRegCode(code);
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			restAPI.init(Constant.SERVER, Constant.PORT);// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(Constant.ACCOUNT, Constant.TOKEN);
			restAPI.setAppId(Constant.APPID);// 初始化应用ID
			result = restAPI.sendTemplateSMS(tel, "100283",
					new String[] { regInfo.getRegCode() });
			if ("000000".equals(result.get("statusCode"))) {
				HashMap<String, Object> data = (HashMap<String, Object>) result
						.get("data");
				Set<String> keySet = data.keySet();
				for (String key : keySet) {
					Object object = data.get(key);
					getLogger().info(key + " = " + object);
				}
				baseDao.saveOrUpdateObject(regInfo);
				resultlist.setState(Constant.HTTP_STATUS_OK);
			} else {
				resultlist.setState(Constant.HTTP_STATUS_FAIL);
				resultlist.setMes((String) result.get("statusMsg"));
				getLogger().info(
						"错误码=" + result.get("statusCode") + " 错误信息= "
								+ result.get("statusMsg"));
			}
		} catch (Exception e) {
			// TODO: handle exception
			getLogger().info(e.getLocalizedMessage());
			resultlist.setState(Constant.HTTP_STATUS_FAIL);
			resultlist.setMes("服务器错误,稍后再试");
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			resultlist.setState(Constant.HTTP_STATUS_FAIL);
			resultlist.setMes(e.getMessage());
		}
		return resultlist;
	}

	/**
	 * 获取激活经销商验证码
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getActiveMes", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Result getActivePlaneMes(HttpServletRequest request,HttpServletResponse response) {
		String tel = request.getParameter("tel");
		String userPhone = request.getParameter("userPhone");
		Result result = new Result<>();

		try {
			if (StringUtils.isEmpty(tel)) {
				throw new ServiceExecption("手机号不能为空！");
			}
			// 查询该飞机是否在对应的经销商下
			String hql1 = "from UavDistributor where distributorPhoneNum='" + tel + "'";
			UavDistributor distributor = (UavDistributor) baseDao.getObjcetReUnique(hql1);
			if (distributor == null) {
				throw new ServiceExecption("该手机号码不是经销商");
			}
			
			// 经销商获取手机验证码
			String hql = "from RegInfo as mdoel where tel='" + tel
					+ "' and mesType='" + Constant.CODE_TYPE_ACTIVE_MES + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			String code = "";
			if (regInfo == null) {
				// 之前未获取过验证码，随机生成一个验证码
				code = RandomUTils.fix(
						String.valueOf((int) (Math.random() * 10000 + 1)), 4);
				regInfo = new RegInfo();
				regInfo.setRegCode(code);
				regInfo.setTel(tel);
				regInfo.setCount(1);
				regInfo.setMesType(Constant.CODE_TYPE_ACTIVE_MES + "");
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
				
			} else {
				// 之前请求过验证码，判断请求间隔是否大于30分钟；不大于30分钟，返回同样的验证码
				// 如果大于30分钟，重新生成验证码
				if ((System.currentTimeMillis() - Long.valueOf(regInfo
						.getExpiredTime())) <= 1000 * 60) {
					result.setState(Constant.HTTP_STATUS_FAIL);
					result.setMes("请求验证码太频繁，请稍后重试");
					return result;
				}
				// 大于30分钟重新生成验证码
				if ((System.currentTimeMillis() - Long.valueOf(regInfo.getExpiredTime())) > 1000 * 60 * 30) {
					regInfo.setRegCode(RandomUTils.fix(
							String.valueOf((int) (Math.random() * 10000 + 1)), 4));
				}

				if ((System.currentTimeMillis() - Long.valueOf(regInfo
						.getExpiredTime())) >= 1000 * 60 * 60 * 24) {
					regInfo.setCount(0);
				}
				regInfo.setExpiredTime(String.valueOf(System
						.currentTimeMillis()));
				regInfo.setCount(regInfo.getCount() + 1);
			}

			HashMap<String, Object> msResult = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			restAPI.init(Constant.SERVER, Constant.PORT);// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(Constant.ACCOUNT, Constant.TOKEN);
			restAPI.setAppId(Constant.APPID);// 初始化应用ID
			msResult = restAPI.sendTemplateSMS(tel, "236918",
					new String[] {userPhone, regInfo.getRegCode() });
			if (StringUtils.equals("000000", (String)msResult.get("statusCode"))) {
				HashMap<String, Object> data = (HashMap<String, Object>) msResult
						.get("data");
				Set<String> keySet = data.keySet();
				for (String key : keySet) {
					Object object = data.get(key);
					getLogger().info(key + " = " + object);
				}
				baseDao.saveOrUpdateObject(regInfo);
				result.setState(Constant.HTTP_STATUS_OK);
				result.setMes("验证码发送成功");
				
			}else {
				result.setState(Constant.HTTP_STATUS_FAIL);
				result.setMes((String)msResult.get("statusMsg"));
			}
		} catch (ServiceExecption e) {
			result.setMes(e.getMes());
			result.setState(Constant.HTTP_STATUS_FAIL);
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("系统异常");
		}
		return result;
	}

}
